/**
 * ReportGear(2011)
 */
package com.reportgear.report.view.grid.pane;

import java.awt.BorderLayout;
import java.awt.Window;

import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;

import net.abbp.swing.util.GuiUtils;

import com.reportgear.core.swing.pane.base.JBasePane;
import net.abbp.core.util.StringUtils;

/**
 * 数数字输入面板
 * 
 * @version 1.0 2011-4-22
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public class NumberInputPane extends JBasePane {
	private JLabel titleLabel;
	private JSpinner numberFieldSpinner;
	private String title;

	public NumberInputPane() {
		super();
		initComponents();
	}

	/**
	 * 显示对话框
	 * 
	 * @param owner
	 *            对话框所属
	 * @return 对话框返回值
	 */
	public int showDialog(Window owner) {
		return this.showDialog(owner, this.title, 180, 100);
	}

	protected void initComponents() {
		this.setLayout(new BorderLayout(4, 4));
		this.titleLabel = new JLabel("");
		this.add(this.titleLabel, BorderLayout.WEST);

		this.numberFieldSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 999, 1));
		GuiUtils.setColumnForSpinner(this.numberFieldSpinner, 12);

		this.add(this.numberFieldSpinner, BorderLayout.CENTER);
	}

	public void setTitle(String title) {
		this.title = title;
		this.titleLabel.setText(title + ":   ");
	}

	public void populate(int value) {
		this.numberFieldSpinner.setModel(new SpinnerNumberModel(0, 0, 999, 1));
		JFormattedTextField ftf = GuiUtils.getSpinnerTextField(this.numberFieldSpinner);
		ftf.setText(StringUtils.convertToString(value));
		ftf.selectAll();
	}

	public void populate(double value) {
		this.numberFieldSpinner.setModel(new SpinnerNumberModel(0.0D, 0.0D, 999.0D, 0.01D));
		JFormattedTextField ftf = GuiUtils.getSpinnerTextField(this.numberFieldSpinner);
		ftf.setText(StringUtils.convertToString(value));
		ftf.selectAll();
	}

	public double update() {
		JFormattedTextField ftf = GuiUtils.getSpinnerTextField(this.numberFieldSpinner);
		try {
			if (ftf.getText().length() == 0)
				return 0.0D;
			return Double.parseDouble(ftf.getText());
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}

		return Double.MAX_VALUE;
	}
}
